﻿using Faser_VoteSys.Models;
using Microsoft.AspNetCore.Mvc;

namespace Faser_VoteSys.Common
{

    /// <summary>
    /// 错误码
    /// [错误类型:1][模块码:2][具体错误码:2]
    /// </summary>
    public class ErrorCodes
    {
        // Code: 1xxxx 模型验证失败
        public const int BASE_MODEL_VALIDATION_FAILED = 10000;
        // Code: 2xxxx 数据库操作失败
        public const int BASE_DB_OPERATION_FAILED = 20000;
        // Code: 3xxxx 业务逻辑错误
        public const int BASE_BUSINESS_LOGIC_ERROR = 30000;

        // Code: -1    服务器内部异常
        public const int SERVER_INTERNAL_ERROR = -1;
    }

    public class ApiError
    {
        static private ObjectResult F_SERVER_ERROR = Build(-1, "服务器内部错误: {0}", null);

        static public ObjectResult DB_NOT_CHANGE = Build(2001, "数据库未发生变化", null);

        static private ObjectResult F_ILLEGAL_INPUT = Build(1000, "不合法的输入: {0}", null);

        static public ObjectResult USER_NOT_FOUND = Build(1001, "用户不存在", null);

        static public ObjectResult USER_PASSWORD_ERROR = Build(1002, "账号或密码错误", null);

        static public ObjectResult USER_ALREADY_EXIST = Build(1003, "用户已存在", null);

        static public ObjectResult NO_FILE_UPLOADED = Build(1004, "未上传文件", null);
        
        static public ObjectResult UNSUPPORTED_FILE_TYPE = Build(1005, "不支持的文件类型", null);

        static public ObjectResult VOTE_COUNT_LIMIT = Build(3001, "今日投票次数已达上限", null);

        static public ObjectResult VOTE_NOT_FOUND_TARGET = Build(3002, "投票目标不存在", null);

        static public ObjectResult ServerInternalError(string reason)
        {
            return Format(F_SERVER_ERROR, reason);
        }

        static public ObjectResult ModelValidationFailed(string reason, object data)
        {
            return FormatAndData(F_ILLEGAL_INPUT, data, reason);
        }


        #region Helper
        static public ObjectResult FormatAndData(ObjectResult apiResponseResult, object data, params object[] param)
        {
            var apiResponse = apiResponseResult.Value as ApiResponse<object>;
            return Build(apiResponse.Code, string.Format(apiResponse.Msg, param), data);
        }

        static public ObjectResult Format(ObjectResult apiResponse, params object[] param)
        {
            return FormatAndData(apiResponse, null, param);
        }

        static public ObjectResult Build(int code, string msg, object data)
        {
            var ret = new ObjectResult(new ApiResponse<object>
            {
                Code = code,
                Msg = msg,
                Data = data
            });
            return ret;
        }
        #endregion

    }
}
